<?php
class YWSTranslations {
    public static function insertNew($value, $locale)
    {
        $guid = YWSUtils::newGuid();
        $model = new PortalTranslations();
        $model->name = $guid;
        
        $model->value = $value;
        $model->locale = $locale;
        $model->insert();
        
        return $guid;
    }
    
    public static function updateTranslation($key, $value, $locale)
    {
        $conn = Yii::app()->db;
        $command = new CDbCommand($conn);
        $rows = $command->update(
                    PortalTranslations::model()->tableName(), 
                    array('value'=>$value), 
                    array('name'=>$key),
                    array('locale'=>$locale)
                );
        if ($rows != 0) return true;
        else return false;
    }

    public static function getTranslation($key, $locale)
    {
        $row = Yii::app()->db->createCommand()
                ->select()->from(PortalTranslations::model()->tableName())
                ->where("name='$key'")
                ->where("locale='$locale'")
                ->queryRow();
        
        // If null return the first item
        if (!$row)
            $row = Yii::app()->db->createCommand()
                ->select()->from(PortalTranslations::model()->tableName())
                ->where("name='$key'")
                ->order("locale asc")
                ->queryRow();        
        
        return $row['value'];
    }

    public static function deleteTranslation($key, $locale)
    {
        $conn = Yii::app()->db;
        $command = new CDbCommand($conn);
        $query = $command->delete(PortalTranslations::model()->tableName(), "name = ".$key);
        if ($query == 0) return false;
        else return true;
    }
}
?>